"""
SCL-90心理评估API序列化器

用于数据验证、序列化和反序列化
"""
from rest_framework import serializers
from typing import Dict, Any
from .models import BasicInfo, SCLAnswers, AssessmentData, generate_test_id
from datetime import datetime


class BasicInfoSerializer(serializers.Serializer):
    """基本信息序列化器"""
    age = serializers.ChoiceField(choices=[
        '18岁以下', '18-25岁', '26-35岁', '36-45岁', 
        '46-55岁', '56-65岁', '65岁以上'
    ])
    gender = serializers.ChoiceField(choices=['男', '女', '其他'])
    occupation = serializers.ChoiceField(choices=[
        '学生', '教师', '医护人员', '企业员工', '公务员', 
        '个体经营', '退休人员', '无业/待业', '其他'
    ])
    sleep_condition = serializers.ChoiceField(choices=[
        '睡眠质量很好', '偶尔失眠', '经常失眠', 
        '严重失眠', '需要药物辅助睡眠'
    ])
    
    def create(self, validated_data):
        """创建BasicInfo对象"""
        return BasicInfo(**validated_data)


class SCLAnswersSerializer(serializers.Serializer):
    """SCL-90答案序列化器"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 动态创建90个题目的字段
        for i in range(1, 91):
            field_name = str(i)
            self.fields[field_name] = serializers.IntegerField(
                min_value=1, 
                max_value=5,
                error_messages={
                    'min_value': f'题目{i}的分数不能小于1',
                    'max_value': f'题目{i}的分数不能大于5',
                    'required': f'题目{i}是必填的'
                }
            )
    
    def validate(self, data):
        """验证答案数据"""
        # 检查是否有90个题目
        expected_questions = set(str(i) for i in range(1, 91))
        actual_questions = set(data.keys())
        
        if expected_questions != actual_questions:
            missing = expected_questions - actual_questions
            extra = actual_questions - expected_questions
            
            error_msg = ""
            if missing:
                error_msg += f"缺少题目: {sorted(missing, key=int)}"
            if extra:
                error_msg += f"多余题目: {sorted(extra, key=int)}"
            
            raise serializers.ValidationError(f"题目数量不正确。{error_msg}")
        
        return data
    
    def create(self, validated_data):
        """创建SCLAnswers对象"""
        return SCLAnswers(answers=validated_data)


class AssessmentSubmissionSerializer(serializers.Serializer):
    """问卷提交序列化器"""
    test_id = serializers.CharField(
        required=False, 
        help_text="测试ID，如果不提供会自动生成"
    )
    basic_info = BasicInfoSerializer()
    scl_answers = SCLAnswersSerializer()
    timestamp = serializers.DateTimeField(
        required=False,
        help_text="提交时间，如果不提供会使用当前时间"
    )
    
    def validate_test_id(self, value):
        """验证测试ID格式"""
        if value:
            # 简单验证UUID格式
            try:
                import uuid
                uuid.UUID(value)
            except ValueError:
                raise serializers.ValidationError("测试ID格式不正确")
        return value
    
    def create(self, validated_data):
        """创建AssessmentData对象"""
        # 生成测试ID（如果没有提供）
        if not validated_data.get('test_id'):
            validated_data['test_id'] = generate_test_id()
        
        # 设置时间戳（如果没有提供）
        if not validated_data.get('timestamp'):
            validated_data['timestamp'] = datetime.now()
        
        # 创建子对象
        basic_info = BasicInfo(**validated_data['basic_info'])
        scl_answers = SCLAnswers(answers=validated_data['scl_answers'])
        
        # 创建完整的评估数据对象
        assessment_data = AssessmentData(
            test_id=validated_data['test_id'],
            basic_info=basic_info,
            scl_answers=scl_answers,
            timestamp=validated_data['timestamp']
        )
        
        return assessment_data


class AssessmentResultSerializer(serializers.Serializer):
    """评估结果序列化器"""
    test_id = serializers.CharField()
    total_score = serializers.IntegerField()
    average_score = serializers.FloatField()
    analysis_report = serializers.CharField()
    recommendations = serializers.CharField()
    risk_level = serializers.ChoiceField(choices=['正常', '轻度困扰', '中度困扰', '较重困扰', '严重困扰'])
    short_url = serializers.CharField()
    created_at = serializers.DateTimeField()


class SubmissionResponseSerializer(serializers.Serializer):
    """提交响应序列化器"""
    success = serializers.BooleanField()
    test_id = serializers.CharField()
    analysis = serializers.CharField()
    short_url = serializers.CharField()
    message = serializers.CharField(required=False)


class ShortUrlRequestSerializer(serializers.Serializer):
    """短链接请求序列化器"""
    test_id = serializers.CharField()
    
    def validate_test_id(self, value):
        """验证测试ID"""
        try:
            import uuid
            uuid.UUID(value)
        except ValueError:
            raise serializers.ValidationError("测试ID格式不正确")
        return value


class ShortUrlResponseSerializer(serializers.Serializer):
    """短链接响应序列化器"""
    short_url = serializers.CharField()


class ErrorResponseSerializer(serializers.Serializer):
    """错误响应序列化器"""
    success = serializers.BooleanField(default=False)
    error = serializers.CharField()
    message = serializers.CharField(required=False)
    details = serializers.DictField(required=False) 